package com.xysoft.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xysoft.admin.common.ActionConst;
import com.xysoft.admin.common.SessionInfo;
import com.xysoft.util.RequestUtil;
import com.xysoft.util.ResourceUtil;

public class AuthInterceptor implements HandlerInterceptor {

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		response.setContentType("text/html; charset=UTF-8");
		// 用户访问的资源地址
		String requestPath = RequestUtil.getRequestPath(request);
		if (requestPath.equals(ActionConst.ADMINLOGINACTION)) {
			return true;
		}
		SessionContext myc= SessionContext.getInstance();
		String sessionId = (String) request.getSession().getAttribute(ResourceUtil.getSessionInfoName());
		SessionInfo sessionInfo = myc.getSession(sessionId);
		if (sessionInfo == null) {
			//RequestUtil.go("login.html", "您没有登录或登录超时，请重新登录！", request, response);
			return false;
		}
		//登录后不需要验证的权限
		if (ActionConst.ADMINNOCHECKEDLOGIN.indexOf(requestPath) != -1) return true;
		List<String> actions = sessionInfo.getActions();
		if (actions.contains(requestPath)) {
			return true;
		}
		else {
			//RequestUtil.forward("/error/authMsg.jsp", "对不起！您没有权限访问该页面！", request, response);
			return false;
		}
	}
}
